﻿using System;
using YanZhiwei.DotNet2.Utilities.Common;
namespace YanZhiwei.DotNet4.Utilities.Common
{
    /// <summary>
    /// Convert帮助类
    /// </summary>
    public static class ConvertHelper
    {
        /// <summary>
        /// 把对象类型转换为指定类型
        /// eg:Assert.AreEqual("true".CastTo<bool>(), true);
        /// <para>rel:http://www.cnblogs.com/guomingfeng/p/extensions.html </para>
        /// </summary>
        /// <param name="value">object</param>
        /// <param name="conversionType">Type</param>
        /// <returns>object</returns>
        public static object CastTo(this object value, Type conversionType)
        {
            if (value == null)
            {
                return null;
            }
            if (conversionType.IsNullableType())
            {
                conversionType = conversionType.GetNonNullableType();
            }
            if (conversionType.IsEnum)
            {
                return Enum.Parse(conversionType, value.ToString());
            }
            if (conversionType == typeof(Guid))
            {
                return Guid.Parse(value.ToString());
            }
            return Convert.ChangeType(value, conversionType);
        }

        /// <summary>
        /// 把对象类型转化为指定类型
        /// <para>eg:Assert.AreEqual("56D768A3-3D74-43B4-BD7B-2871D675CC4B".CastTo<Guid>(), new Guid("56D768A3-3D74-43B4-BD7B-2871D675CC4B"));</para>
        /// <para>rel:http://www.cnblogs.com/guomingfeng/p/extensions.html </para>
        /// </summary>
        /// <typeparam name="T"> 动态类型 </typeparam>
        /// <param name="value"> 要转化的源对象 </param>
        /// <returns> 转化后的指定类型的对象，转化失败引发异常。 </returns>
        public static T CastTo<T>(this object value)
        {
            object result = CastTo(value, typeof(T));
            return (T)result;
        }

        /// <summary>
        /// 把对象类型转化为指定类型，转化失败时返回指定的默认值
        /// <para>eg:Assert.AreEqual("true".CastTo<bool>(), true);</para>
        /// <para>rel:http://www.cnblogs.com/guomingfeng/p/extensions.html </para>
        /// </summary>
        /// <typeparam name="T"> 动态类型 </typeparam>
        /// <param name="value"> 要转化的源对象 </param>
        /// <param name="defaultValue"> 转化失败返回的指定默认值 </param>
        /// <returns> 转化后的指定类型对象，转化失败时返回指定的默认值 </returns>
        public static T CastTo<T>(this object value, T defaultValue)
        {
            try
            {
                return CastTo<T>(value);
            }
            catch (Exception)
            {
                return defaultValue;
            }
        }
    }
}
